"use strict";
var webwx = require('./src/webwx'),
    child_process = require('child_process'),
    net = require('net'),
    robot = require('./src/robot'),
    autoreply = require('./src/autoreply'),
    config = require('./config').config;

// 开启服务
var p1 = new Promise((resolve, reject) => {
    var server = net.createServer(function (socket) {
        console.info("client connected! %j:%j", socket.remoteAddress, socket.remotePort);
        var serverSession = {
            server: server,
            socket: socket
        }
        resolve(serverSession);
        socket.on("data", function (data) {
            console.info("recived from client:", data.toString());
        });
        socket.on("close", function (had_error) {
            if (!had_error) {
                console.info("client closed success! %j:%j", socket.remoteAddress, socket.remotePort);
            }
            else {
                console.info("client close error! %j:%j", socket.remoteAddress, socket.remotePort);
            }
        })
        socket.on("error", function (err) {
            console.error("!!!err!!!", err);
            process.exit(0)
        });
    });
    server.listen({
        port: config.server.port
    }, function () {
        var address = server.address();
        console.info(" opened server on address %j ", address);
    });
});


var display_window = child_process.spawn('cmd.exe', ['/s', '/c', 'nw qrcode_window/.']);

/*var display_window = child_process.exec('nw "qrcode_window/."', (error, stdout, stderr) => {
    if (error) {
        console.error(`exec error: ${error}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
});*/
display_window.stdout.on('data', function (s) {
    console.log(s.toString());
});

// 微信web方法
var checkAndParseUUID = webwx.checkAndParseUUID;
var showQRImg = webwx.showQRImg;
var checkLogin = webwx.checkLogin;
var parseAndRedirect = webwx.parseAndRedirect;
var wxLogin = webwx.wxLogin;
var getBaseRequest = webwx.getBaseRequest;
var webWechatInit = webwx.webWechatInit;
var webWechatGetContact = webwx.webWechatGetContact;
// 对于信息响应
var autoreplyRes = autoreply.autoreplyRes;

p1.then(function (serverSession) {
    serverSession.display = display_window;

    webwx.getUUID
        .then(checkAndParseUUID)
        .then(showQRImg(serverSession))
        .then(checkLogin)
        .then(parseAndRedirect)
        .then(wxLogin)
        .then(getBaseRequest)
        .then(webWechatInit)
        .then(webWechatGetContact)
        .then(robot.robot(
            [(wxSession) => o => true],
            [autoreplyRes]))
        .catch((e) => {
            console.log("系统错误" + e);
            console.log(e);
            process.exit(1);
        });
});